<?php

namespace App\Modules\Apicrzs\Services\Buy;

use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use App\Modules\Admin\Entities\Water\WaterWithUserModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Traits\CryptAES;

class WaterDeviceService extends BaseServices
{
    public function __construct(WaterDeviceModel $model)
    {
        $token = \request()->header('token');
        $user_info = CryptAES::decryptToken($token, 'user_grzq');
        $this->user_id = $user_info['data']['user_id'] ?? "";
        $this->model = $model;
    }

    public function getLists($params){
        $user_id = $this->user_id;
        $waterList =  WaterWithUserModel::getInstance()->getUserWithWaterByIds($user_id);

        $waterIds = array_keys($waterList);
        $model = $this->model->with([
            'community_info' => function($query) {
                $query->select('id', 'title');
            },
        ]);
        $model = $model->where(['status'=>1]);
        $model = $model->whereIn('water_id',$waterIds);
        $lists = $model->orderBy($this->model->getKeyName(), 'DESC')
            ->paginate($this->getLimit($params['limit'] ?? 10));

        $lists_data=[];
        foreach ($lists->items() as $item){
            $lists_data[]=[
                'id'=>$item['water_id'],
                'title'=>$item['water_title'],
                'code'=>$item['code'],
                'type'=>$item['type'],
                'address'=>$item['address'],
                'lng'=>$item['lng'],
                'lat'=>$item['lat'],
                'remaining'=>999,//天数
                'signed_at'=>$item['signed_at'],
                'community_info'=>$item['community_info']??[]
            ];
        }

        return [
            'current_page' => $lists->currentPage(),//当前
            'per_page'     => $lists->perPage(),//每页 10 条
            'count_page'   => $lists->lastPage(),//
            'total'        => $lists->total(), // 总数
            'data'         => $lists_data,
        ];
    }

    public function getApparatusScoreSum($apparatus_id){

        return 10;
    }

    public function getWaterCount($userId){
        $user_id = $this->user_id;
        $apparatusList =  WaterWithUserModel::getInstance()->getUserWithWaterByIds($user_id);
        $count = count($apparatusList);
        return ['count' => $count];
    }

}
